import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

class Solution {
     public class TreeNode {
         int val;
         TreeNode left;
         TreeNode right;
         TreeNode() {}
         TreeNode(int val) { this.val = val; }
         TreeNode(int val, TreeNode left, TreeNode right) {
             this.val = val;
             this.left = left;
             this.right = right;
         }
     }

    //层序遍历
    public List<Integer> largestValues(TreeNode root) {
        if(root == null) return new LinkedList<>();
        List<Integer> ret = new ArrayList<>();
        Queue<TreeNode> queue = new LinkedList<>();//存储每层的节点
        queue.offer(root);
        int max;
        while(!queue.isEmpty()){
            int levelSize = queue.size();
            max = Integer.MIN_VALUE;
            for (int i = 0; i < levelSize; i++) {
                TreeNode node = queue.poll();
                if(max < node.val) max = node.val;
                if(node.left != null){
                    queue.offer(node.left);
                }
                if(node.right != null){
                    queue.offer(node.right);
                }
            }
            ret.add(max);//将每一层的最大值加入ret
        }
        return ret;
    }
}